package com.juyu.miliao.api.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.juyu.miliao.api.dao.mysql.OrderDao;
import com.juyu.miliao.api.dao.redis.PayNotifySGRedisDao;
import com.juyu.miliao.api.domain.Order;

@Service
public class PayNotifySGService {
	@Resource
	private OrderDao orderDao;
	@Resource
	private PayNotifySGRedisDao payNotifySGRedisDao;
	@Resource
	private ConfigAppService configAppService;
//	private static final String sg_notify_url = "http://pay.5ayg.cn:30002/sg-pay/miLiao";
	private static final String sg_notify_url = "http://pay.c6829063.com:30002/sg-pay/miLiao";
	private static final int notify_num = 3;
	private final	Logger payNotifyLogger = LoggerFactory.getLogger("payNotify");

	public void notifySG(String orderId) {
		try {
			payNotifyLogger.info("开始同步给单机后台数据--------orderId={}",orderId);
			Optional<Order> optOrder = Optional.ofNullable(orderDao.findOrderByOrderId(orderId));
			if (!optOrder.isPresent()) {
				payNotifyLogger.error("同步给单机后台数据错误----数据不存在----orderId={}",orderId);
				return;
			}
			Order order = optOrder.get();
			Map<String, String> parameters = new HashMap<>();
			parameters.put("payTime", order.getPayTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
			parameters.put("fee", order.getFee()+"");
			parameters.put("orderNo", order.getOrderId());
			parameters.put("channelId", order.getChannelId());
			parameters.put("payType",order.getContentType()+"");
			Integer packageGroup= configAppService.getPackageGroup(order.getAppPackageId(),order.getPhoneSystem()+"");
			if (packageGroup!=null){
				if(packageGroup==0){ //马甲包
					if(order.getAppPackageId().equals("tcyl") && order.getPhoneSystem()==1){
						parameters.put("gameId", "1001"); //同城夜聊-Android
					}else if(order.getAppPackageId().equals("tcyl") && order.getPhoneSystem()==2){
						parameters.put("gameId", "1002"); //同城夜聊-IOS
					}else if(order.getAppPackageId().equals("mmjy") && order.getPhoneSystem()==1){
						parameters.put("gameId", "1004"); //陌陌约会-android
					}else if(order.getAppPackageId().equals("mmjy") && order.getPhoneSystem()==2){
						parameters.put("gameId", "1003"); //陌陌约会-ios
					}else if(order.getAppPackageId().equals("miban") && order.getPhoneSystem()==1){
						parameters.put("gameId", "2000"); //密伴安卓
					}else if(order.getAppPackageId().equals("miban") && order.getPhoneSystem()==2){
						parameters.put("gameId", "2001"); //密伴ios
					}
				}else if(packageGroup==1){ //线上包
					if(order.getPhoneSystem()==1){
						parameters.put("gameId", "1000"); //花蜜-android
					}else{
						parameters.put("gameId", "999"); //花蜜-ios
					}
				}else if(packageGroup==2){ //黑白包
					if(order.getPhoneSystem()==1){
						parameters.put("gameId", "1005"); //黑白包-android
					}else{
						parameters.put("gameId", "1006"); //黑白包-ios
					}
				}
			}
			int sdkId = 0;
			//支付类型：1支付宝 2 微信 3applePay
			if(order.getPayType() ==1){
				sdkId = 58698;
			}else if(order.getPayType() ==2){
				sdkId = 58699;
			}else if(order.getPayType() ==3){
				sdkId = 58765;
			}
			parameters.put("sdkId", sdkId+"");
			String accessUrl = sg_notify_url+returnAccessUrl(parameters);
			payNotifyLogger.info("开始同步给单机后台数据----开始调用get请求----orderId={},accressUrl={}",orderId,accessUrl);
			String responseStr= doGet(accessUrl);
			payNotifyLogger.info("开始同步给单机后台数据----get请求结果----responseStr={}",responseStr);
			if(responseStr==null || !responseStr.equals("ok")){
				payNotifyLogger.info("开始同步给单机后台数据----get请求结果失败进入轮询----responseStr={},orderId={}",responseStr,orderId);
				JSONObject json = new JSONObject();
				json.put("accessUrl",accessUrl);
				json.put("notifyNum",notify_num-1);
				payNotifySGRedisDao.notifySGRedisScheduler(optOrder.get(),json.toString());
			}
		}catch (Exception e){
			if(payNotifyLogger.isErrorEnabled()){
				payNotifyLogger.error("同步单机后台异常:",e);
			}
		}
	}

	private String returnAccessUrl(Map<String, String> parameters){
		StringBuffer param = new StringBuffer();
		try {
		int i = 0;
		for (String key : parameters.keySet()) {
			if (i == 0)
				param.append("?");
			else
				param.append("&");
			param.append(key).append("=").append(URLEncoder.encode(parameters.get(key), "UTF-8"));
			i++;
		}} catch (Exception e) {
			payNotifyLogger.info("开始同步给单机后台数据----开始调用get请求:请求异常----missage={}", e);
		}
		return param.toString();
	}

	private String doGet(String accessUrl) throws Exception {
		String response = null;
				HttpURLConnection httpURLConnection = null;
				BufferedReader br = null;
				try {
					payNotifyLogger.info("开始同步给单机后台数据----开始调用get请求:下单地址----url={}", accessUrl);
					URL url = new URL(accessUrl);
					httpURLConnection = (HttpURLConnection) url.openConnection();
					br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
					String readLine = null;
					StringBuffer sb = new StringBuffer();
					while ((readLine = br.readLine()) != null) {
						sb.append(readLine);
					}
					response = sb.toString();
				} catch (Exception e) {
					throw new Exception("开始同步给单机后台数据----开始调用get请求:请求异常----missage={}", e);
				} finally {
					httpURLConnection.disconnect();
					try {
				if (br != null) {
					br.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return response;
	}


}
